import router from '@/router'
import store from '@/store'
import NProgress from 'nprogress' // 引入一份进度条插件
import 'nprogress/nprogress.css' // 引入进度条样式

const writeList = ['/login', '/404']
// 路由前置守卫
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  if (store.getters.token) {
    if (to.path === '/login') {
      next('/')
      setTimeout(function() {
        NProgress.done()
      }, 500)
    } else {
      if (!store.state.user.userInfo.userId) {
        const { roles: { menus }} = await store.dispatch('user/getInfo')
        // console.log(menus)
        const res = await store.dispatch('permission/filterRouter', menus)
        router.addRoutes([...res, { path: '*', redirect: '/404', hidden: true }])
        // 1.根据menus删选对应的路由
        // 2.将筛选的路由添加到路由规则中router.addRoutes([{path:xxx,component : xx},{},{}])
        // 3.临时添加所有的动态路由测试router.addRoutes
        next({
          ...to,
          replace: true// 重新进一次，不保留重读历史
        })
      }
      next()
    }
  } else {
    if (writeList.includes(to.path)) {
      next()
    } else {
      next('/login')
      setTimeout(function() {
        NProgress.done()
      }, 500)
    }
  }
})
// 路由后置守卫
router.afterEach((to, from) => {
  setTimeout(function() {
    NProgress.done()
  }, 500)
})
